package com.jungle.admin.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import com.jungle.common.config.properties.SecurityProperties;
import com.jungle.common.json.JacksonObjectMapper;
import com.jungle.system.interceptor.JwtTokenUserInterceptor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Configuration
@RequiredArgsConstructor
@Slf4j
public class WebMvcConfiguration implements WebMvcConfigurer  /*extends WebMvcConfigurationSupport */ {
    //    private final JwtTokenUserInterceptor jwtTokenUserInterceptor;
    private final SecurityProperties securityProperties;

    /**
     * 注册自定义拦截器
     *
     * @param registry
     */
    public void addInterceptors(InterceptorRegistry registry) {
        log.info("注册 Sa-Token 拦截器...");
        registry.addInterceptor(new SaInterceptor(handle -> {
//                    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
//                            .getRequestAttributes()).getRequest();
//                    log.info("请求地址：{}", request.getRequestURI());
                    StpUtil.checkLogin();
                }))
                .addPathPatterns("/**")
                .excludePathPatterns(securityProperties.getExcludes());
    }

    /**
     * 扩展MVC框架的消息转换器
     *
     * @param converters
     */
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        log.info("开始扩展消息转换器...");
        //创建一个消息转换器
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        //设置对象转换器，可以将java对象转为json串
        converter.setObjectMapper(new JacksonObjectMapper());
        //将自己的转换器放MVC容器中
        converters.add(/*0,*/ converter);
    }
}


